import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { ConfirmationService } from 'primeng/api';
import { FieldType } from 'src/components/scenarios/enums';
import { PlcDataField } from 'src/components/scenarios/models';
import { v4 as guid } from "uuid";
import { DataFieldSettingDialogComponent } from '../data-field-setting-dialog/data-field-setting-dialog.component';
@Component({
  selector: 'app-field-list',
  templateUrl: './field-list.component.html',
  styleUrl: './field-list.component.scss',
})
export class FieldListComponent {

  private _fields: PlcDataField[] = [];
  @Input()
  public get fields(): PlcDataField[] {
    return this._fields;
  }
  public set fields(value: PlcDataField[]) {
    this._fields = value;
    this.fieldsChange.emit(this._fields);
  }

  @Output()
  fieldsChange: EventEmitter<PlcDataField[]> = new EventEmitter();

  @ViewChild("settingDialog", { static: true })
  settingDialog!: DataFieldSettingDialogComponent;


  constructor(private confirmService: ConfirmationService) {

  }

  onEditField(field: PlcDataField) {
    this.settingDialog.onShow(field);
  }

  onDeleteField(field: PlcDataField) {
    console.log(field);
    this.confirmService.confirm({
      message: 'Do you want to delete this field?',
      header: 'Delete Confirmation',
      icon: 'pi pi-info-circle',
      acceptButtonStyleClass: "p-button-danger p-button-text",
      rejectButtonStyleClass: "p-button-text p-button-text",
      acceptIcon: "none",
      rejectIcon: "none",

      accept: () => {
        console.log("Accept");
        this.fields = this.fields.filter(f => f.Id !== field.Id);
      },
      reject: () => {
      }
    });
  }

  onDragDrop(event: CdkDragDrop<PlcDataField[]>) {
    moveItemInArray(this.fields, event.previousIndex, event.currentIndex);
  }
  onAddFieldClick() {
    const field: PlcDataField = {
      Id: "",
      Name: "",
      Address: "",
      Type: FieldType.Int16
    };
    this.settingDialog.onShow(field);
  }

  onFiedEditConfirm(field: PlcDataField) {
    console.log("onFiedEditConfirm");
    if (field.Id) {
      this.fields = this.fields.map(f => f.Id === field.Id ? field : f);
    }
    else {
      this.fields.push({ ...field, Id: guid() });
    }
  }
}
